跳到主要内容

interface

接口声明是命名对象类型的另一种方式:

interface Point {
x: number;
y: number;
}

function printCoord(pt: Point) {}

类型别名和接口之间的区别

类型别名和接口非常相似,在许多情况下,您可以自由选择它们。 几乎所有的功能都 interface 可以在 type 中使用 ,关键区别在于类型不能重新打开以添加新属性,而接口始终可以扩展。

type Window = {
title: string;
}

type Window = {
ts: TypeScriptAPI; // Error: Duplicate identifier 'Window'.
}

除非您需要使用 type 中的功能。否则推荐 interface。

interface 与 type 的主要区别以下:

  1. type 能够表示非对象类型,而 interface 只能表示对象类型(包括数组、函数等)。
  2. interface 可以继承其他类型,type 不支持继承。
  3. 同名 interface 会自动合并,同名 type 则会报错。
  4. interface 不能包含属性映射(mapping)
  5. this 关键字只能用于 interface。
  6. type 可以扩展原始数据类型,interface 不行。
  7. interface 无法表达某些复杂类型(比如交叉类型和联合类型),但是 type 可以。
interface Point {
x: number;
y: number;
}

// 正确
type PointCopy1 = {
[Key in keyof Point]: Point[Key];
};

// 报错
interface PointCopy2 {
[Key in keyof Point]: Point[Key];
};

// 正确
interface Foo {
add(num: number): this;
}

// 报错
type Foo = {
add(num: number): this,
};
// 正确
interface Foo {
add(num: number): this;
}

// 报错
type Foo = {
add(num: number): this,
};
type A = {
/* ... */
};
type B = {
/* ... */
};

type AorB = A | B;
type AorBwithName = AorB & {
name: string,
};

参考链接

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#interfaces